<template>
	<el-dialog :title="isEdit?'编辑资料':'添加资料'" @opened="opened" v-bind="$attrs" v-on="$listeners" width="460px">
		<div class="form">
			<el-form :model="form" :rules="rules" class="demo-ruleForm" label-width="70px" ref="form">
				<el-form-item label="文件夹" prop="folderId">
					<!-- <el-tree :data="tree" :expand-on-click-node="false" @node-click="checkChange" accordion node-key="id">
						<div class="custom-tree-node" slot-scope="{  data }">
							<div class="name-warp">
								<i class="el-icon-folder"></i>
								<span class="name">{{ data.folderName }}({{data.counts}})</span>
							</div>
							<div class="icon" v-if="data.check">
								<i class="success el-icon-success"></i>
							</div>
						</div>
					</el-tree>-->

					<el-cascader
						:options="tree"
						:props="{ checkStrictly: true,emitPath:false }"
						class="cascader"
						clearable
						placeholder="请选择目标文件夹"
						v-model="form.folderId"
					></el-cascader>
				</el-form-item>
				<el-form-item :label="`附件`" prop="fileVOS" v-if="!isEdit">
					<el-upload
						:before-upload="beforeUpload"
						:file-list="fileVOS"
						:http-request="httpRequest"
						:on-remove="fileUploadRemove"
						:on-success="fileImportSuccess"
						accept=".pdf"
						action="#"
						class="upload-demo"
						drag
						multiple
						ref="upload"
					>
						<i class="el-icon-upload"></i>
						<div class="el-upload__text">
							将文件拖到此处，或
							<em>点击上传</em>
						</div>
						<div class="el-upload__tip" slot="tip">只能上传pdf文件，且不超过30M</div>
					</el-upload>
				</el-form-item>
			</el-form>
		</div>

		<span class="dialog-footer" slot="footer">
			<el-button @click="close">取 消</el-button>
			<el-button @click="confirm" type="primary">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
import Api from './api'
import _ from 'lodash'
function setCheck(data) {
	data.forEach(el => {
		el.label = el.folderName
		el.value = el.id
		// el.check = false
		if (el.children && el.children.length) {
			setCheck(el.children)
		} else {
			delete el.children
		}
	})
	return data
}
export default {
	props: {
		/**
		 * 表单数据，用于数据回显
		 */
		formData: {
			type: Object,
			default: function () {
				return {}
			}
		},
		/**
		 * 获取文件夹树形数据的方法
		 */
		getTree: {
			required: true,
			type: Function
		},
		/**
		 * 确定提交的方法
		 */
		submit: {
			required: true,
			type: Function
		},
		/**
		 * 过滤数据的方法
		 */
		filterData: Function
	},
	watch: {
		formData(val) {
			if (val && !_.isEmpty(val)) {
				this.form = {
					folderId: val.folderId || '',
					fileVOS: val.fileVOS || [],
					id: val.id
				}
			} else {
				this.form = {
					folderId: '',
					fileVOS: []
				}
			}
		}
	},
	computed: {
		isEdit() {
			return this.form.id
		}
	},
	data() {
		return {
			form: {
				folderId: '',
				fileVOS: []
			},
			rules: {
				folderId: [{ required: true, message: '请选择要上传文件目录', trigger: 'change' }],
				fileVOS: [{ required: true, message: '请选择要上传的附件', trigger: 'change' }]
			},
			fileVOS: [],
			tree: []
		}
	},
	methods: {
		async getTreeData() {
			const res = await this.getTree()
			const data = this.filterData ? this.filterData(_.cloneDeep(res)) : _.cloneDeep(res)
			this.tree = setCheck(data)
		},
		async httpRequest(config) {
			const formData = new FormData()
			formData.append('files', config.file) // 和后端约定好的名称
			formData.append('type', config.file.type) // 和后端约定好的类型
			return await Api.uploadFile(formData)
		},
		fileImportSuccess(res) {
			this.form.fileVOS = this.form.fileVOS.concat(res)
		},
		fileUploadRemove(res) {
			this.form.fileVOS = this.form.fileVOS.filter(item => item.id !== res.id)
		},
		beforeUpload(file) {
			if (file.size > 30 * 1024 * 1000) {
				this.err('文件' + file.name + '超过上传大小限制，请重新选择', 5000)
				return false
			}
		},
		close() {
			this.$refs.form.resetFields()
			this.fileVOS = []
			this.$emit('update:visible', false)
		},
		opened() {
			this.getTreeData()
		},
		async confirm() {
			if (!this.isEdit) {
				const hasFileUploading = this.$refs.upload.uploadFiles.some(item => item.status === 'uploading' || item.status === 'ready')
				if (hasFileUploading) {
					return this.err('有附件正在上传，请稍等')
				}
			}
			this.$refs.form.validate(async valid => {
				if (valid) {
					try {
						await this.submit({
							...this.form
						})
						/**
						 * @description 新增或修改成功后的回调
						 * @event success
						 * @type {Event}
						 */
						this.$emit('success', this.form.folderId, this.isEdit)
						this.ok(this.isEdit ? '修改成功' : '新增成功')
						this.close()
					} catch (error) {
						this.err(this.isEdit ? '修改失败' : '新增失败')
					}
				} else {
					this.scrollIntoView()
					return false
				}
			})
		}
	}
}
</script>
<style lang="scss" scoped>
.cascader {
	width: 100%;
}
.custom-tree-node {
	align-content: center;
	font-size: 14px;
	line-height: 28px;
	flex: 1;
	position: relative;
	.name-warp {
		margin-right: 76px;
		.name {
			margin-left: 5px;
		}
	}
	.icon {
		position: absolute;
		right: 0;
		top: 0;
		i {
			margin-left: 5px;
			margin-right: 5px;
		}
		.success {
			color: $color-success !important;
		}
	}
}
</style>
